import React, { useState, useEffect } from 'react';

const GlobalTimeFilter = ({ onTimePeriodChange }) => {
  const [currentTimePeriod, setCurrentTimePeriod] = useState('day');

  useEffect(() => {
    // 初始化时触发一次时间范围变化
    handleTimePeriodChange(currentTimePeriod);
  }, []);

  const handleTimePeriodChange = (period) => {
    setCurrentTimePeriod(period);
    
    // 更新当前时间参数
    const timeParam = getCurrentTimeParam(period);
    
    // 触发时间范围变化回调
    if (onTimePeriodChange) {
      onTimePeriodChange({
        period: period,
        param: timeParam
      });
    }
  };

  // 获取当前时间参数
  const getCurrentTimeParam = (period) => {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');

    switch(period) {
      case 'year':
        return year.toString();
      case 'month':
        return `${year}-${month}`;
      case 'day':
        return `${year}-${month}-${day}`;
      default:
        return `${year}-${month}-${day}`;
    }
  };

  return (
    <div id="global-time-filter">
      <div 
        className={`time-filter ${currentTimePeriod === 'day' ? 'active' : ''}`} 
        onClick={() => handleTimePeriodChange('day')}
        data-period="day"
      >
        本日
      </div>
      <div 
        className={`time-filter ${currentTimePeriod === 'month' ? 'active' : ''}`} 
        onClick={() => handleTimePeriodChange('month')}
        data-period="month"
      >
        本月
      </div>
      <div 
        className={`time-filter ${currentTimePeriod === 'year' ? 'active' : ''}`} 
        onClick={() => handleTimePeriodChange('year')}
        data-period="year"
      >
        本年
      </div>
      
      <style>{`
        #global-time-filter {
          position: absolute;
          top: 20px;
          right: 20px;
          display: flex;
          gap: 15px;
          z-index: 1000;
        }
        
        .time-filter {
          padding: 8px 20px;
          background: rgba(10, 58, 124, 0.5);
          border: 1px solid rgba(36, 187, 236, 0.3);
          color: #a2d3e8;
          border-radius: 4px;
          cursor: pointer;
          font-size: 18px;
          transition: all 0.3s ease;
        }
        
        .time-filter.active {
          background: rgba(36, 187, 236, 0.2);
          color: #24bbec;
          font-weight: bold;
          box-shadow: 0 0 10px rgba(36, 187, 236, 0.5);
        }
        
        .time-filter:hover {
          transform: translateY(-3px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
      `}</style>
    </div>
  );
};

export default GlobalTimeFilter;